#ifndef FLV_WRITER_H
#define FLV_WRITER_H

#include <cstring>
#include <stdio.h>
#include <iostream>

#include <mutex>
#include <chrono>
#include <thread>

#include "Tools.h"

#define FLV_HEADER_LENGTH 13
#define FLV_TAG_HEADER_LENGTH 11
#define PFRAME_PREFIX_LENGTH 10
#define FLV_SCRIPT_TAG_LENGTH 199
#define FLV_SCRIPT_TAG_WIDTH_OFFSET 0x38
#define FLV_SCRIPT_TAG_HEIRHT_OFFSET 0x49
#define FLV_SCRIPT_TAG_FRAMERATE_OFFSET 0x75

#define FLV_WRITER_LOG false

class FlvWriter
{
private:
    //flv文件写入
    FILE* file;//测试写入目标
    char* recBuffer;
    float frameRate;

    //套接字写入
    int clientFd;

    bool hasScriptTag;//是否写入了ScriptTag和AVCSeq
    int h264SPSLength;
    char H264SPS[200];
    int h264PPSLength;
    char H264PPS[50];

    uint8_t IDRPrefix[300];
    int IDRPrefixLength;
    int AVCSeqFrameLength;

    int curNaluLength;
    DataNode* sendNode;
    bool active;
    std::mutex mtxActive;

    int lastestIDRIndex;
    std::mutex mtxIDRIndex;

public:
    FlvWriter(char* _recBuffer, float _frameRate, int _flvClientSocketFd, DataNode* _sendNode);
    ~FlvWriter();

    //各种帧类型的解析器
    void NaluHandler();
    bool SPSHandler();
    bool PPSHandler();
    bool IDRHandler();
    bool PFrameHandler();
    bool AfterGetSPSAndPPS();

    //启动flv线程
    static void FlvThread(FlvWriter* flvWriter);
    void SetActive(bool _active);
    bool GetActive();
    void SetLastestIDR(int index);
    int GetLastestIDR();

    DataNode* GetSendNode();
};

#endif